package com.study.server;

import com.study.server.codec.MessageDecoder;
import com.study.server.codec.MessageEncoder;
import com.study.server.handler.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by meen on 2017/12/4.
 */
public class TcpServer implements Runnable {

    private int port;

    public TcpServer(int port) {
        this.port = port;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();//线程组
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap boot = new ServerBootstrap();//server启动管理配置
            boot.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)//服务端可连接队列数为1024
                    .childOption(ChannelOption.SO_REUSEADDR, true) //重用地址
                    .childOption(ChannelOption.SO_RCVBUF, 65536)
                    .childOption(ChannelOption.SO_SNDBUF, 65536)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(false))  // heap buf 's better
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //这里我们先不写代码，这里主要是添加业务处理handler
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("decoder", new MessageDecoder());
                            pipeline.addLast("handler", new NettyServerHandler());
                            pipeline.addLast("encoder", new MessageEncoder());
                        }
                    });
            ChannelFuture f = boot.bind(port).sync();
            if (f.isSuccess()) {
                System.out.println("Server starts success at port:" + port);
            }
            f.channel().closeFuture().sync();//这里会导致线程阻塞
            //这里可以添加警报,表示服务器已down
        } catch (Exception e) {
//            e.printStackTrace();
            System.err.println("Server starts failed at port:" + port + " cause:" + e.getMessage());
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

}
